package com.xls.commonlibrary.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.orhanobut.logger.Logger;
import com.xls.commonlibrary.app.MainApplication;
import com.xls.commonlibrary.bean.UpdateVersionResult;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class VersionCodeUtil {

    // 检测是否需要更新等
    public static boolean isNeedUpdate(UpdateVersionResult updateVersionResult) {
        boolean result = false;
        String serverCode = updateVersionResult.getVersionCode();
        if (!TextUtils.isEmpty(serverCode)) {
            int newerCode = Integer.parseInt(serverCode);
            int apkCode = VersionCodeUtil.getVersionCode();
            result = newerCode > apkCode;
        }

        Logger.d("========isNeedUpdate=============" + result);

        return result;
    }


    public static boolean isForceUpdate(UpdateVersionResult updateVersionResult) {
        boolean result = false;
        String forceUpdate = updateVersionResult.getForceUpdate();
        if (!TextUtils.isEmpty(forceUpdate)) {
            result = "1".equals(forceUpdate);// 1 强制更新
        }

        Logger.d("========isForceUpdate=============" + result);

        return result;
    }


    // md5
    public static String computeMD5(File file) {
        if (file == null) return "wrong";

        DigestInputStream din = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            //第一个参数是一个输入流
            din = new DigestInputStream(new BufferedInputStream(new FileInputStream(file)), md5);

            byte[] b = new byte[1024];
            while (din.read(b) != -1) ;

            byte[] digest = md5.digest();
            StringBuilder result = new StringBuilder(byte2Hex(digest));

            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (din != null) {
                    din.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // return null;
        return "wrong";
    }

    public static String byte2Hex(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        StringBuilder builder = new StringBuilder();
        // 遍历byte[]数组，将每个byte数字转换成16进制字符，再拼接起来成字符串
        for (int i = 0; i < bytes.length; i++) {
            // 每个byte转换成16进制字符时，bytes[i] & 0xff如果高位是0，输出将会去掉，所以+0x100(在更高位加1)，再截取后两位字符
            builder.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        return builder.toString();
    }


    // file size


    public static int getVersionCode() {
        int code = 0;
        Context context = MainApplication.getAppContext();
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);

            code = packageInfo.versionCode;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        Logger.d("===========getVersionCode==============:" + code);

        return code;
    }

    public static String getVersionName() {
        String versionName = "";
        Context context = MainApplication.getAppContext();
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);

            versionName = packageInfo.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        Logger.d("===========getVersionName==============:" + versionName);

        return versionName;
    }
}
